#!/usr/bin/env bash

set -e

if [[ "$SSH_ENABLE" == "1" ]]; then
    PG_HOME=$(eval echo ~postgres)

    mkdir -p $PG_HOME/.ssh/ || echo '.ssh dir exists'
    cp -f /tmp/.ssh/config $PG_HOME/.ssh/ || echo 'No pre-populated ssh configs!'
    cp -f /tmp/.ssh/keys/* $PG_HOME/.ssh/ || echo 'No pre-populated ssh keys!'
    chown -R postgres:postgres $PG_HOME
    echo '>>> TUNING UP SSH CLIENT...'
    if [ ! -f "$PG_HOME/.ssh/id_rsa.pub" ] && [ ! -f "$PG_HOME/.ssh/id_rsa" ]; then
        echo ">>>  There are no ssh keys - SSH daemon can not be enabled!"
        exit 1
    fi

    chmod 600 -R $PG_HOME/.ssh/id_rsa

    mkdir -p /var/run/sshd && sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
    sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
    echo "export VISIBLE=now" >> /etc/profile

    cat $PG_HOME/.ssh/id_rsa.pub >> $PG_HOME/.ssh/authorized_keys

    echo '>>> STARTING SSH SERVER...'
    /usr/sbin/sshd 2>&1
else
    echo ">>> SSH is not enabled!"
fi
